package com.bite.blog.controller;

import com.bite.blog.model.Blog;
import com.bite.blog.service.BlogService;
import com.bite.blog.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/blog")
@RestController
public class BlogController {
    private static final String TOKEN_HEADER = "user_token_head";
    
    @Autowired
    private BlogService blogService;
    // 获取博客列表
    @RequestMapping("/getList")
    public List<Blog> getList() {
        log.info("获取博客列表：");
        return blogService.getList();
    }

    // 查询文章详情
    @RequestMapping("/getBlogDetail")
    public Blog getBlogDetail(@RequestParam("blogId") Integer id, HttpServletRequest request) {
        log.info("查询文章详情： id=" + id);
        if (id == null) {
            throw new UnsupportedOperationException();
        }
        // 判断是否是当前登录用户的文章
        String token = request.getHeader(TOKEN_HEADER);
        Assert.notNull(token, "用户未登录");
        Integer userId = JwtUtils.getUserId(token);
        Blog blog = blogService.getBlogDetail(id);
        // 设置
        blog.setLoginUser(blog.getUserId().equals(userId));
//        blog.setIsLoginUser(blog.getUserId().equals(userId));
        return blog;
    }

    // 添加文章
    @RequestMapping("/add")
    public Boolean addBlog(@Validated @RequestBody Blog blog, HttpServletRequest request) {
        log.info("添加文章：blog" + blog);
        String token = request.getHeader(TOKEN_HEADER);
        Assert.notNull(token, "用户未登录");
        Integer userId = JwtUtils.getUserId(token);
        blog.setUserId(userId);
        Integer row = null;
        try {
            row = blogService.insertBlog(blog);
        } catch (Exception e) {
            log.error("博客添加失败, e: {}", e.getMessage());
        }
        return row != null && row.equals(1);
    }

    // 更新博客
    @RequestMapping("/update")
    public Boolean update(@Validated @RequestBody Blog blog) {
        log.info("更新博客：blogId=" + blog.getId());
        Integer result = null;
        try {
            result = blogService.update(blog);
        } catch (Exception e) {
            log.error("博客更新失败：", e);
        }
        return result != null && result >= 1;
    }

    // 删除博客
    @RequestMapping("delete")
    public Boolean delete(Integer blogId) {
        log.info("删除文章 blogID=" + blogId);
        Assert.notNull(blogId, "blogId不能为空");
        Integer result = null;
        try {
            result = blogService.delete(blogId);
        } catch (Exception e) {
            log.error("博客删除失败：", e);
        }
        return result != null && result >= 1;
    }
}
